import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class MainGUI extends JFrame {
    private ClassManager classManager;
    private StudentManager studentManager;
    private RandomCaller randomCaller;
    private ScoreRecorder scoreRecorder;
    
    private JComboBox<String> classComboBox;
    private JComboBox<String> groupComboBox;
    private JList<String> studentList;
    private JTextArea outputArea;
    
    public MainGUI() {
        // 初始化管理器
        classManager = new ClassManager();
        studentManager = new StudentManager();
        randomCaller = new RandomCaller();
        scoreRecorder = new ScoreRecorder();
        
        // 设置窗口
        setTitle("班级管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(10, 10));
        
        // 创建面板
        add(createLeftPanel(), BorderLayout.WEST);
        add(createCenterPanel(), BorderLayout.CENTER);
        add(createRightPanel(), BorderLayout.EAST);
        add(createBottomPanel(), BorderLayout.SOUTH);
        
        // 设置窗口居中显示
        setLocationRelativeTo(null);
    }
    
    private JPanel createLeftPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.setPreferredSize(new Dimension(200, 0));
        
        // 班级选择
        JLabel classLabel = new JLabel("班级:");
        classComboBox = new JComboBox<>();
        JButton addClassButton = new JButton("添加班级");
        
        // 小组选择
        JLabel groupLabel = new JLabel("小组:");
        groupComboBox = new JComboBox<>();
        JButton addGroupButton = new JButton("添加小组");
        
        // 设置组件首选大小
        Dimension comboBoxSize = new Dimension(180, 25);
        classComboBox.setPreferredSize(comboBoxSize);
        classComboBox.setMaximumSize(comboBoxSize);
        groupComboBox.setPreferredSize(comboBoxSize);
        groupComboBox.setMaximumSize(comboBoxSize);
        
        Dimension buttonSize = new Dimension(180, 30);
        addClassButton.setPreferredSize(buttonSize);
        addClassButton.setMaximumSize(buttonSize);
        addGroupButton.setPreferredSize(buttonSize);
        addGroupButton.setMaximumSize(buttonSize);
        
        // 添加事件监听器
        addClassButton.addActionListener(e -> showAddClassDialog());
        addGroupButton.addActionListener(e -> showAddGroupDialog());
        
        classComboBox.addActionListener(e -> updateGroupComboBox());
        groupComboBox.addActionListener(e -> updateStudentList());
        
        // 添加组件到面板
        panel.add(classLabel);
        panel.add(Box.createVerticalStrut(5));
        panel.add(classComboBox);
        panel.add(Box.createVerticalStrut(5));
        panel.add(addClassButton);
        panel.add(Box.createVerticalStrut(15));
        panel.add(groupLabel);
        panel.add(Box.createVerticalStrut(5));
        panel.add(groupComboBox);
        panel.add(Box.createVerticalStrut(5));
        panel.add(addGroupButton);
        
        return panel;
    }
    
    private JPanel createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        JLabel studentLabel = new JLabel("学生列表:");
        studentList = new JList<>();
        studentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(studentList);
        
        JButton addStudentButton = new JButton("添加学生");
        addStudentButton.addActionListener(e -> showAddStudentDialog());
        
        panel.add(studentLabel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(addStudentButton, BorderLayout.SOUTH);
        
        return panel;
    }
    
    private JPanel createRightPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.setPreferredSize(new Dimension(150, 0));
        
        JButton[] buttons = {
            new JButton("随机点名"),
            new JButton("添加分数"),
            new JButton("记录考勤"),
            new JButton("显示统计")
        };
        
        Dimension buttonSize = new Dimension(130, 30);
        for (JButton button : buttons) {
            button.setPreferredSize(buttonSize);
            button.setMaximumSize(buttonSize);
            button.setAlignmentX(Component.CENTER_ALIGNMENT);
            panel.add(button);
            panel.add(Box.createVerticalStrut(10));
        }
        
        buttons[0].addActionListener(e -> showRandomCallDialog());
        buttons[1].addActionListener(e -> showAddScoreDialog());
        buttons[2].addActionListener(e -> showRecordAttendanceDialog());
        buttons[3].addActionListener(e -> showStatistics());
        
        return panel;
    }
    
    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        outputArea = new JTextArea(4, 40);
        outputArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(outputArea);
        
        panel.add(scrollPane, BorderLayout.CENTER);
        return panel;
    }
    
    private void showAddClassDialog() {
        String className = JOptionPane.showInputDialog(this, 
            "请输入班级名称:", "添加班级", JOptionPane.PLAIN_MESSAGE);
        
        if (className != null && !className.trim().isEmpty()) {
            classManager.addClass(className);
            updateClassComboBox();
            outputArea.append("已添加班级: " + className + "\n");
        }
    }
    
    private void showAddGroupDialog() {
        String selectedClass = (String) classComboBox.getSelectedItem();
        if (selectedClass == null) {
            JOptionPane.showMessageDialog(this, "请先选择班级", "警告", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String groupName = JOptionPane.showInputDialog(this, 
            "请输入小组名称:", "添加小组", JOptionPane.PLAIN_MESSAGE);
        
        if (groupName != null && !groupName.trim().isEmpty()) {
            classManager.getClassGroups(selectedClass).addGroup(groupName);
            updateGroupComboBox();
            outputArea.append("已添加小组: " + groupName + "\n");
        }
    }
    
    private void showAddStudentDialog() {
        String selectedClass = (String) classComboBox.getSelectedItem();
        String selectedGroup = (String) groupComboBox.getSelectedItem();
        
        if (selectedClass == null || selectedGroup == null) {
            JOptionPane.showMessageDialog(this, "请先选择班级和小组", "警告", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String studentName = JOptionPane.showInputDialog(this, 
            "请输入学生姓名:", "添加学生", JOptionPane.PLAIN_MESSAGE);
        
        if (studentName != null && !studentName.trim().isEmpty()) {
            classManager.getClassGroups(selectedClass).addStudentToGroup(selectedGroup, studentName);
            studentManager.addStudentToGroup(selectedGroup, studentName);
            studentManager.addStudentToClass(selectedClass, studentName);
            updateStudentList();
            outputArea.append("已添加学生: " + studentName + "\n");
        }
    }
    
    private void showRandomCallDialog() {
        String selectedClass = (String) classComboBox.getSelectedItem();
        if (selectedClass == null) {
            JOptionPane.showMessageDialog(this, "请先选择班级", "警告", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String[] options = {"从班级", "从小组", "取消"};
        int choice = JOptionPane.showOptionDialog(this, 
            "请选择随机点名范围", "随机点名",
            JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
            null, options, options[0]);
        
        if (choice == 0) {
            List<String> classStudents = studentManager.getStudentsInClass(selectedClass);
            if (!classStudents.isEmpty()) {
                String randomStudent = randomCaller.getRandomStudentFromClass(classStudents);
                outputArea.append("随机选中学生: " + randomStudent + "\n");
            } else {
                JOptionPane.showMessageDialog(this, "班级中没有学生", "提示", 
                    JOptionPane.INFORMATION_MESSAGE);
            }
        } else if (choice == 1) {
            String selectedGroup = (String) groupComboBox.getSelectedItem();
            if (selectedGroup != null) {
                List<String> groupStudents = classManager.getClassGroups(selectedClass)
                    .getStudentsInGroup(selectedGroup);
                if (!groupStudents.isEmpty()) {
                    String randomStudent = randomCaller.getRandomStudentFromGroup(groupStudents);
                    outputArea.append("随机选中学生: " + randomStudent + "\n");
                } else {
                    JOptionPane.showMessageDialog(this, "小组中没有学生", "提示", 
                        JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }
    }
    
    private void showAddScoreDialog() {
        String selectedStudent = studentList.getSelectedValue();
        if (selectedStudent == null) {
            JOptionPane.showMessageDialog(this, "请先选择学生", "警告", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String scoreStr = JOptionPane.showInputDialog(this, 
            "请输入分数:", "添加分数", JOptionPane.PLAIN_MESSAGE);
        
        if (scoreStr != null && !scoreStr.trim().isEmpty()) {
            try {
                int score = Integer.parseInt(scoreStr);
                scoreRecorder.addStudentScore(selectedStudent, score);
                outputArea.append("已为 " + selectedStudent + " 添加分数: " + score + "\n");
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", 
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void showRecordAttendanceDialog() {
        String selectedStudent = studentList.getSelectedValue();
        if (selectedStudent == null) {
            JOptionPane.showMessageDialog(this, "请先选择学生", "警告", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String[] options = {"出勤", "缺勤"};
        int choice = JOptionPane.showOptionDialog(this,
            "请选择 " + selectedStudent + " 的考勤状态", "记录考勤",
            JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
            null, options, options[0]);
        
        if (choice != -1) {
            boolean present = (choice == 0);
            scoreRecorder.recordStudentAttendance(selectedStudent, present);
            outputArea.append("已记录 " + selectedStudent + 
                " 的考勤状态: " + (present ? "出勤" : "缺勤") + "\n");
        }
    }
    
    private void showStatistics() {
        StringBuilder stats = new StringBuilder();
        stats.append("===== 统计信息 =====\n");
        stats.append("学生分数: ").append(scoreRecorder.getStudentScores()).append("\n");
        stats.append("小组分数: ").append(scoreRecorder.getGroupScores()).append("\n");
        stats.append("考勤记录: ").append(scoreRecorder.getStudentAttendance()).append("\n");
        
        outputArea.setText(stats.toString());
    }
    
    private void updateClassComboBox() {
        classComboBox.removeAllItems();
        for (String className : classManager.getClassList()) {
            classComboBox.addItem(className);
        }
    }
    
    private void updateGroupComboBox() {
        groupComboBox.removeAllItems();
        String selectedClass = (String) classComboBox.getSelectedItem();
        if (selectedClass != null) {
            for (String groupName : classManager.getClassGroups(selectedClass).getGroupList()) {
                groupComboBox.addItem(groupName);
            }
        }
        updateStudentList();
    }
    
    private void updateStudentList() {
        DefaultListModel<String> listModel = new DefaultListModel<>();
        String selectedClass = (String) classComboBox.getSelectedItem();
        String selectedGroup = (String) groupComboBox.getSelectedItem();
        
        if (selectedClass != null && selectedGroup != null) {
            List<String> students = classManager.getClassGroups(selectedClass)
                .getStudentsInGroup(selectedGroup);
            for (String student : students) {
                listModel.addElement(student);
            }
        }
        
        studentList.setModel(listModel);
    }
    
    public static void main(String[] args) {
        // 使用系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 在 EDT 中创建并显示 GUI
        SwingUtilities.invokeLater(() -> {
            MainGUI gui = new MainGUI();
            gui.setVisible(true);
        });
    }
} 